package com.mvvm.base.base

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import com.alibaba.android.arouter.launcher.ARouter
import com.mvvm.base.BuildConfig
import com.mvvm.base.util.prefs.SharedPreferencesManager
import com.mvvm.base.logger.initLogger
import com.mvvm.base.util.DateUtil
import com.mvvm.base.util.MD5

import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.androidModule
import org.kodein.di.android.x.androidXModule
import org.kodein.di.generic.bind
import org.kodein.di.generic.singleton
import java.util.HashMap

open class BaseApplication : Application(), KodeinAware, Application.ActivityLifecycleCallbacks  {
    private var activityMap = HashMap<String, Activity>()

    override val kodein: Kodein = Kodein.lazy {
        bind<Context>() with singleton { this@BaseApplication }
        import(androidModule(this@BaseApplication))
        import(androidXModule(this@BaseApplication))

    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        if (BuildConfig.DEBUG) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog()     // 打印日志
            ARouter.openDebug()   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        val req_date = DateUtil.timeStamp2Date2(DateUtil.timestamp_13.toString() + "", "yyyyMMddHH24MMSS")
        val sessionId = MD5(req_date + 2 + "gialen_APP")
        SharedPreferencesManager.Companion.instance!!.saveString(SharedPreferencesManager.SPCommons.SESSIONID, sessionId)

        ARouter.init(this)

        initLogger(BuildConfig.DEBUG)

    }


    companion object {

        @get:Synchronized
        lateinit var instance: BaseApplication
    }

    override fun onActivityPaused(activity: Activity) {
    }

    override fun onActivityStarted(activity: Activity) {
    }
    override fun onActivityResumed(activity: Activity) {
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
    }
    override fun onActivityStopped(activity: Activity) {
    }


    override fun onActivityDestroyed(activity: Activity) {
        activityMap[activity.hashCode().toString() + ""] = activity
        for (key in activityMap.keys) {
            activityMap.remove(key)
        }
    }



    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        activityMap[activity.hashCode().toString() + ""] = activity
    }


    fun exitApp() {
        for (activity in activityMap.values) {
            activity.finish()
        }
    }
}